package com.gutai.admin.service.impl;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.aliyun.oss.model.PutObjectResult;
import com.gutai.admin.common.util.OSSUtil;
import com.gutai.admin.common.util.StringUtil;
import com.gutai.admin.entity.dto.ImageSize;
import com.gutai.admin.entity.dto.ImageSizeMap;
import com.gutai.admin.service.IFileService;
import com.sun.image.codec.jpeg.ImageFormatException;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

/**
 * 
 * 描述：
 * 
 * <pre>
 * HISTORY
 * ****************************************************************************
 *  ID    DATE            PERSON            REASON
 *  1     2018年11月7日         YC           Create
 * ****************************************************************************
 * </pre>
 * 
 * @author YC
 * @version 1.0
 */
@Service
public class FileService implements IFileService {
    private static final Logger logger = LoggerFactory.getLogger(FileService.class);
    private static ImageSizeMap imageSizeMap = new ImageSizeMap();
    static {
        /* goods pic size */
        imageSizeMap.put("/goods/listPicUrl", 800, 800);
        imageSizeMap.put("/goods/primaryPicUrl", 800, 800);

        /* goods Desc */
        imageSizeMap.put("/goods/goodsDesc", 750, 200);

        /* ad imageUrl */
        imageSizeMap.put("/ad/imageUrl", 1440, 800);
        /* brand pic size */
        imageSizeMap.put("/brand/listPicUrl", 750, 240);
        imageSizeMap.put("/brand/appListPicUrl", 1440, 800);
        imageSizeMap.put("/brand/picUrl", 760, 484);
        imageSizeMap.put("/brand/newPicUrl", 760, 484);

        /* category pic size */
        imageSizeMap.put("/category/bannerUrl", 1090, 360);
        imageSizeMap.put("/category/imgUrl", 720, 360);
        imageSizeMap.put("/category/iconUrl", 90, 90);
        imageSizeMap.put("/category/wapBannerUrl", 750, 246);

        /* goods gallery pic size */
        imageSizeMap.put("/goodsGallery/imgUrl", 800, 800);

        /* goodsSpecification pic size */
        imageSizeMap.put("/goodsSpecification/picUrl", 200, 200);

    }
    /**
     *
     * @param file
     * @return
     */
    @Override
    public String putObject(String bucketName, String clazz, String columnName, File file) {

        String objectKey = StringUtil.generateObjectKey(clazz, columnName, file.getName());
        String localPath = null;
        try {
            localPath = resize("/" + clazz + "/" + columnName, file.getParent() + "/resized_"
                    + file.getName(), file);
        } catch (ImageFormatException e) {
            logger.info("file ImageFormat Exception: {}", e);
        } catch (IOException e) {
            logger.info("file IO Exception: {}", e);
        }
        PutObjectResult putObjectResult = OSSUtil.putObject(bucketName,objectKey,localPath);
        if (null == localPath) {
            return null;
        }

        return OSSUtil.generateOSSURI(objectKey);
    }
    private String resize(String columnName, String savePath, File targetFile) throws ImageFormatException, IOException {
        if ("/goods/goodsDesc".equals(columnName)) {
            return targetFile.getParent() + "/" + targetFile.getName();
        }
        BufferedImage image = ImageIO.read(targetFile);
 
        ImageSize imageSize = imageSizeMap.get(columnName);
        System.out.println("columnName is : " + columnName);
        System.out.println("width is : " + imageSize.getWidth() + "heiht is : "
                + imageSize.getHeight());
        return resize(imageSize.getWidth(),imageSize.getHeight(), savePath, image);
    }

    private static String resize(int width, int height, String savePath, BufferedImage targetImage)
            throws ImageFormatException, IOException {
        width = Math.max(width, 1);
        height = Math.max(height, 1);
        BufferedImage image = new BufferedImage(width, height, targetImage.getType());
        image.getGraphics().drawImage(targetImage, 0, 0, width, height, null);
        System.out.print(savePath);
        FileOutputStream fos = new FileOutputStream(new File(savePath));
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(fos);
        JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(image);

        jep.setQuality(1f, true);
        encoder.encode(image, jep);

        image.flush();
        fos.flush();
        fos.close();

        return savePath;
    }


}
